//
//  SLContactService.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/2/25.
//

#import "SLContactService.h"
#import <Contacts/Contacts.h>


@interface SLContactService ()
@property (nonatomic, copy  ) void(^completion)(NSArray *obj);
@end

@interface SLContactService ()
@property (nonatomic, strong) SLContactService *owner;
@end

@implementation SLContactService

- (void)retainSelf {
    self.owner = self;
}
- (void)releaseSelf {
    self.owner = nil;
}

+ (instancetype)startContactWithCompletion:(void(^)(NSArray *obj))completion {
    SLContactService *contact = [SLContactService new];
    contact.completion = completion;
    [contact retainSelf];
    [contact requestContactPermission];
    return contact;
}

/// 请求权限
- (void)requestContactPermission {
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        // 请求权限
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"通讯录访问权限已授权");
                [self fetchContacts]; // 获取通讯录
            } else {
                NSLog(@"通讯录访问权限被拒绝");
            }
        }];
    } else if (status == CNAuthorizationStatusAuthorized) {
        // 已经授权，直接获取通讯录
        [self fetchContacts];
    } else {
        // 权限被拒绝或受限
        NSLog(@"通讯录访问权限被拒绝或受限");
    }
}


// 获取通讯录数据
- (void)fetchContacts {
    CNContactStore *store = [[CNContactStore alloc] init];
    NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    NSString *containerId = store.defaultContainerIdentifier;
    NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
    NSError *error;
    NSArray *contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
    
    if (error) {
        NSLog(@"获取通讯录失败: %@", error.localizedDescription);
        return;
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    for (CNContact *contact in contacts) {
        NSString *firstName = contact.givenName;
        NSString *lastName = contact.familyName;
        NSLog(@"姓名: %@ %@", firstName, lastName);
        NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
        
        NSMutableArray *phones = [NSMutableArray array];
        for (CNLabeledValue *phoneNumber in contact.phoneNumbers) {
            NSString *label = phoneNumber.label;
            CNPhoneNumber *number = phoneNumber.value;
            NSLog(@"电话 (%@): %@", label, number.stringValue);
            [phones addObject:number.stringValue];
        }
        
        // 组装上报对象
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:fullName forKey:@"veins"];
        [dict setValue:[phones componentsJoinedByString:@","] forKey:@"strides"];
        [arr addObject:dict];
    }
    
    !self.completion ?: self.completion(arr);
}

@end
